package com.zbkj.service.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zbkj.common.model.TransferOrder;
import com.zbkj.common.model.TransferOrderDetails;
import com.zbkj.common.model.Warehouse;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.product.Product;
import com.zbkj.common.model.product.ProductAttrValue;
import com.zbkj.common.model.saleroom.RoomProduct;
import com.zbkj.common.model.saleroom.SaleRoom;
import com.zbkj.common.model.saleroom.TransferInfo;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.*;
import com.zbkj.common.response.SaleRoomOrWarehouseResponse;
import com.zbkj.common.response.TransferOrderProductAttrValueResponse;
import com.zbkj.common.utils.SecurityUtil;
import com.zbkj.common.vo.LoginUserVo;
import com.zbkj.service.dao.ProductAttrValueDao;
import com.zbkj.service.dao.TransferOrderDao;
import com.zbkj.service.dao.TransferOrderDetailsDao;
import com.zbkj.service.dao.WarehouseDao;
import com.zbkj.service.dao.saleroom.RoomProductDao;
import com.zbkj.service.dao.saleroom.SaleRoomDao;
import com.zbkj.service.dao.saleroom.TransferInfoDao;
import com.zbkj.service.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;


/**
 * @author keNan
 * @description TransferOrderServiceImpl 接口实现
 * @date 2025-06-12
 */
@Service
public class TransferOrderServiceImpl extends ServiceImpl<TransferOrderDao, TransferOrder> implements TransferOrderService {

    @Autowired
    private TransferOrderDao dao;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductAttrValueDao productAttrValueDao;
    @Autowired
    private RoomProductDao roomProductDao;
    @Autowired
    private WarehouseDao warehouseDao;
    @Autowired
    private SaleRoomDao saleRoomDao;
    @Autowired
    private TransferOrderDetailsDao transferOrderDetailsDao;
    @Autowired
    private TransferOrderDetailsService transferOrderDetailsService;
    @Autowired
    private ProductCategoryService productCategoryService;
    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Autowired
    private TransferInfoDao transferInfoDao;


    /**
     * 列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<TransferOrder>
     * @author keNan
     * @since 2025-06-12
     */
    @Override
    public List<TransferOrder> getList(TransferOrderSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<TransferOrder> list = dao.getListBySearch(request);
        return list;
    }


    /**
     * 新增门店、仓库调货单
     *
     * @param transferOrderRequest
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addTransferOrder(TransferOrderRequest transferOrderRequest) {
        TransferOrder transferOrder = new TransferOrder();
        BeanUtils.copyProperties(transferOrderRequest, transferOrder);
        //查询转出仓库或者门店名称
        if (1 == transferOrderRequest.getTransferOutType()) {
            Warehouse warehouse = warehouseDao.selectById(transferOrderRequest.getTransferOutStoreId());
            transferOrder.setTransferOutStore(warehouse != null ? warehouse.getWarehouseName() : "");
        } else {
            SaleRoom saleRoom = saleRoomDao.selectById(transferOrderRequest.getTransferOutStoreId());
            transferOrder.setTransferOutStore(saleRoom != null ? saleRoom.getRoomName() : "");
        }
        //查询转入仓库或者门店名称
        if (1 == transferOrderRequest.getTransferInType()) {
            Warehouse warehouse = warehouseDao.selectById(transferOrderRequest.getTransferInStoreId());
            transferOrder.setTransferInStore(warehouse != null ? warehouse.getWarehouseName() : "");
        } else {
            SaleRoom saleRoom = saleRoomDao.selectById(transferOrderRequest.getTransferInStoreId());
            transferOrder.setTransferInStore(saleRoom != null ? saleRoom.getRoomName() : "");
        }
        //计算总调货数量
        int sum = transferOrderRequest.getTransferOrderSkuListRequest().stream().mapToInt(TransferOrderSkuListRequest::getNumber).sum();
        transferOrder.setTotalNumber(sum)
                //暂直接通过
                .setAuditStatus(2)
                .setTransferOrderSkuListJsonStr(JSONArray.toJSONString(transferOrderRequest.getTransferOrderSkuListRequest()))
                .setReceiptNumber(StrUtil.format("{}{}", "DB", System.currentTimeMillis()))
                .setCreateTime(new Date());

        Optional.ofNullable(SecurityUtil.getLoginUserVo())
                .map(LoginUserVo::getUser)
                .map(SystemAdmin::getRealName)
                .ifPresent(realName -> {
                    transferOrder.setDocumentPreparer(realName);
                });
        //保存门店、仓库调货单
        save(transferOrder);


        List<TransferOrderDetails> transferOrderDetailsList = new ArrayList<>();
        Date date = new Date();
        transferOrderRequest.getTransferOrderSkuListRequest().forEach(productAttrValue -> {
            productAttrValue.setImage(systemAttachmentService.clearPrefix(productAttrValue.getImage()));
            TransferOrderDetails transferOrderDetails = new TransferOrderDetails();
            BeanUtils.copyProperties(transferOrder, transferOrderDetails);
            BeanUtils.copyProperties(productAttrValue, transferOrderDetails);
            transferOrderDetails.setTransferOrderId(transferOrder.getId())
                    .setCreateTime(date)
                    .setTransferOutNumber(productAttrValue.getNumber());
            transferOrderDetailsList.add(transferOrderDetails);
        });

        //保存门店、仓库调货单详情
        transferOrderDetailsService.saveBatch(transferOrderDetailsList);

        //新增原调货详情记录
        TransferInfo transferInfo = new TransferInfo();
        transferInfo.setTransferType(1)
                .setTransferTime(new Date())
                .setTransferRoomId(transferOrderRequest.getTransferInStoreId());

        List<TransferInfoRequest> transferInfoRequestList = new ArrayList<>();
        transferOrderRequest.getTransferOrderSkuListRequest().forEach(t -> {
            TransferInfoRequest transferInfoRequest = new TransferInfoRequest();
            transferInfoRequest.setProductSpecsId(t.getProductAttrValueId())
                    .setTransferNumber(t.getNumber())
                    .setTransferRoomName(transferOrder.getTransferInStore());
            //查询规格名称
            ProductAttrValue productAttrValue = productAttrValueDao.selectById(t.getProductAttrValueId());
            transferInfoRequest.setProductAttrValue(productAttrValue != null ? productAttrValue.getSku() : "");
            Product product = productService.getById(productAttrValue.getProductId());
            transferInfoRequest.setProductName(product != null ? product.getName() : "")
                    .setProductId(product != null ? product.getId() : null);

            transferInfoRequestList.add(transferInfoRequest);
        });
        transferInfo.setTransferJson(JSON.toJSONString(transferInfoRequestList));
        transferInfoDao.insert(transferInfo);


        //审核通过
        if (false) {
//        if (2 == transferOrder.getAuditStatus()) {
            //TransferOrder transferOrder = getById(reviewRequest.getId());
            String transferOrderSkuListJsonStr = transferOrder.getTransferOrderSkuListJsonStr();
            List<TransferOrderSkuListRequest> transferOrderSkuListRequestList = JSONArray.parseArray(transferOrderSkuListJsonStr, TransferOrderSkuListRequest.class);
            //调入为门店时要在eb_room_product表添加库存
            if (2 == transferOrder.getTransferInType()) {
                transferOrderSkuListRequestList.forEach(t -> {
                    LambdaQueryWrapper<RoomProduct> lqw = new LambdaQueryWrapper();
                    lqw.eq(RoomProduct::getRoomId, transferOrder.getTransferInStoreId());
                    lqw.eq(RoomProduct::getProductSpecsId, t.getProductAttrValueId());
                    RoomProduct roomProduct = roomProductDao.selectOne(lqw);
                    if (null != roomProduct) {
                        roomProduct.setProductStore(roomProduct.getProductStore() + t.getNumber());
                        roomProductDao.updateById(roomProduct);
                    } else {
                        ProductAttrValue productAttrValue = productAttrValueDao.selectById(t.getProductAttrValueId());
                        RoomProduct r = new RoomProduct()
                                //TODO
//                                .setTransferInfoId(transferOrder.getId())
//                                .setRoomId(transferOrder.getTransferInStoreId())
                                .setProductId(productAttrValue.getProductId())
                                .setRoomId(transferOrder.getTransferInStoreId())
                                .setTransferInfoId(transferInfo.getId())
                                .setProductSpecsId(t.getProductAttrValueId())
                                .setProductStore(t.getNumber())
                                .setIsSure(0)
                                .setCreateTime(new Date());
                        roomProductDao.insert(r);
                    }
                });
            }
            //调出为门店时要在eb_room_product表减去库存
            if (2 == transferOrder.getTransferOutType()) {
                transferOrderSkuListRequestList.forEach(t -> {
                    LambdaQueryWrapper<RoomProduct> lqw = new LambdaQueryWrapper();
                    lqw.eq(RoomProduct::getRoomId, transferOrder.getTransferInStoreId());
                    lqw.eq(RoomProduct::getProductSpecsId, t.getProductAttrValueId());
                    RoomProduct roomProduct = roomProductDao.selectOne(lqw);
                    if (null != roomProduct) {
                        roomProduct.setProductStore(roomProduct.getProductStore() - t.getNumber());
                        roomProductDao.updateById(roomProduct);
                    }
                });

            }
        }

        return true;
    }


    /**
     * 新增调货单-查询商品规格
     *
     * @param productAttrValueSearchRequest
     * @return
     */
    @Override
    public PageInfo<TransferOrderProductAttrValueResponse> selectProductAttrValueList(ProductAttrValueSearchRequest productAttrValueSearchRequest) {
        List<TransferOrderProductAttrValueResponse> outList = null;
        List<TransferOrderProductAttrValueResponse> inList = null;
        Page<TransferOrderProductAttrValueResponse> page = null;
        List<Integer> categoryIdList = null;
        if (null != productAttrValueSearchRequest.getCategoryId()) {
            //查询三级商品分类id列表
            categoryIdList = productCategoryService.listByCategoryId(productAttrValueSearchRequest.getCategoryId());
        }

        //转出仓库或者门店
        if (1 == productAttrValueSearchRequest.getTransferOutType()) {
            //查询转出仓库下的商品id
            List<Integer> productIdList = productService.getIdListByWarehouseId(productAttrValueSearchRequest.getTransferOutStoreId());

            page = PageHelper.startPage(productAttrValueSearchRequest.getPage(), productAttrValueSearchRequest.getLimit());
            outList = productAttrValueDao.selectProductAttrValueList(productAttrValueSearchRequest, productAttrValueSearchRequest.getTransferOutStoreId(), productIdList, categoryIdList);
        } else {
            //查询转出门店下的商品
            page = PageHelper.startPage(productAttrValueSearchRequest.getPage(), productAttrValueSearchRequest.getLimit());
            outList = roomProductDao.selectProductAttrValueList(productAttrValueSearchRequest, productAttrValueSearchRequest.getTransferOutStoreId(), categoryIdList);
        }
        PageHelper.clearPage();
        //转入仓库或者门店
        if (1 == productAttrValueSearchRequest.getTransferInType()) {
            //查询转入仓库下的规格库存数
            //查询转出仓库下的商品id
            List<Integer> productIdList = productService.getIdListByWarehouseId(productAttrValueSearchRequest.getTransferInStoreId());
            inList = productAttrValueDao.selectProductAttrValueList(productAttrValueSearchRequest, productAttrValueSearchRequest.getTransferInStoreId(), productIdList, categoryIdList);
        } else {
            inList = roomProductDao.selectProductAttrValueList(productAttrValueSearchRequest, productAttrValueSearchRequest.getTransferInStoreId(), categoryIdList);
        }
        List<TransferOrderProductAttrValueResponse> finalInList = inList;
        outList.forEach(out -> {
            finalInList.forEach(in -> {
                if (out.getProductAttrValueId().equals(in.getProductAttrValueId())) {
                    out.setTransferInStoreThenStock(in.getTransferOutStoreThenStock() == null ? 0 : in.getTransferOutStoreThenStock());
                }
            });
        });
        return CommonPage.copyPageInfo(page, outList);
    }


    /**
     * 查询门店、仓库调货单详情信息
     *
     * @param idRequest
     * @return
     */
    @Override
    public PageInfo<TransferOrderDetails> info(IdRequest idRequest) {
        Page<TransferOrderDetails> page = PageHelper.startPage(idRequest.getPage(), idRequest.getLimit());
        LambdaQueryWrapper<TransferOrderDetails> lqw = new LambdaQueryWrapper<>();
        lqw.eq(TransferOrderDetails::getTransferOrderId, idRequest.getId());
        List<TransferOrderDetails> transferOrderDetailsList = transferOrderDetailsDao.selectList(lqw);
        transferOrderDetailsList.forEach(transferOrderDetails -> {
            transferOrderDetails.setTransferOutStoreThenStock(transferOrderDetails.getTransferOutStoreThenStock() == null ? 0 : transferOrderDetails.getTransferOutStoreThenStock());
            transferOrderDetails.setTransferInStoreThenStock(transferOrderDetails.getTransferInStoreThenStock() == null ? 0 : transferOrderDetails.getTransferInStoreThenStock());
        });

        return CommonPage.copyPageInfo(page, transferOrderDetailsList);
    }


    /**
     * 审核
     *
     * @param reviewRequest
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean review(ReviewRequest reviewRequest) {
        LambdaUpdateWrapper<TransferOrder> luw = new LambdaUpdateWrapper();
        luw.set(TransferOrder::getAuditStatus, reviewRequest.getAuditStatus());
        luw.eq(TransferOrder::getId, reviewRequest.getId());
        update(luw);
        //审核通过
        if (2 == reviewRequest.getAuditStatus()) {
            TransferOrder transferOrder = getById(reviewRequest.getId());
            String transferOrderSkuListJsonStr = transferOrder.getTransferOrderSkuListJsonStr();
            List<TransferOrderSkuListRequest> transferOrderSkuListRequestList = JSONArray.parseArray(transferOrderSkuListJsonStr, TransferOrderSkuListRequest.class);
            //调入为门店时要在eb_room_product表添加库存
            if (2 == transferOrder.getTransferInType()) {
                transferOrderSkuListRequestList.forEach(t -> {
                    LambdaQueryWrapper<RoomProduct> lqw = new LambdaQueryWrapper();
                    lqw.eq(RoomProduct::getRoomId, transferOrder.getTransferInStoreId());
                    lqw.eq(RoomProduct::getProductSpecsId, t.getProductAttrValueId());
                    RoomProduct roomProduct = roomProductDao.selectOne(lqw);
                    if (null != roomProduct) {
                        roomProduct.setProductStore(roomProduct.getProductStore() + t.getNumber());
                        roomProductDao.updateById(roomProduct);
                    } else {
                        RoomProduct r = new RoomProduct()
                                .setTransferInfoId(transferOrder.getId())
                                .setRoomId(transferOrder.getTransferInStoreId())
                                .setProductSpecsId(t.getProductAttrValueId())
                                .setProductStore(t.getNumber())
                                .setIsSure(1)
                                .setCreateTime(new Date());
                        roomProductDao.insert(r);
                    }
                });
            }
            //调出为门店时要在eb_room_product表减去库存
            if (2 == transferOrder.getTransferOutType()) {
                transferOrderSkuListRequestList.forEach(t -> {
                    LambdaQueryWrapper<RoomProduct> lqw = new LambdaQueryWrapper();
                    lqw.eq(RoomProduct::getRoomId, transferOrder.getTransferInStoreId());
                    lqw.eq(RoomProduct::getProductSpecsId, t.getProductAttrValueId());
                    RoomProduct roomProduct = roomProductDao.selectOne(lqw);
                    if (null != roomProduct) {
                        roomProduct.setProductStore(roomProduct.getProductStore() - t.getNumber());
                        roomProductDao.updateById(roomProduct);
                    }
                });

            }
        }


        return true;
    }


    /**
     * 根据类型分页查询仓库或者门店
     *
     * @param typeRequest
     * @return
     */
    @Override
    public PageInfo<SaleRoomOrWarehouseResponse> listByType(TypeRequest typeRequest) {
        Page<SaleRoomOrWarehouseResponse> page = PageHelper.startPage(typeRequest.getPage(), typeRequest.getLimit());
        List<SaleRoomOrWarehouseResponse> list = null;
        if (1 == typeRequest.getType()) {
            list = warehouseDao.listByType();
        } else {
            list = saleRoomDao.listByType();
        }
        return CommonPage.copyPageInfo(page, list);
    }


}

